package spring.security.core.util;

import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import com.google.common.base.Strings;

public class CharsetUtils {

	public static final String US_ASCII = "US-ASCII";
	public static final String ISO_8859_1 = "ISO-8859-1";
	public static final String UTF_8 = "UTF-8";
	public static final String UTF_16BE = "UTF-16BE";
	public static final String UTF_16LE = "UTF-16LE";
	public static final String UTF_16 = "UTF-16";
	public static final String GBK = "GBK";
	public static final Charset DEFAULT_CHARSET_UTF8 = Charset.forName("UTF-8");
	public static final Charset CHARSET_GBK = Charset.forName("GBK");

	public static final String toASCII(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "US-ASCII");
	}

	public static final String toISO_8859_1(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "ISO-8859-1");
	}

	public static String toUTF_8(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "UTF-8");
	}

	public static final String toUTF_16BE(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "UTF-16BE");
	}

	public static final String toUTF_16LE(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "UTF-16LE");
	}

	public static final String toUTF_16(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "UTF-16");
	}

	public static final String toGBK(String str) throws UnsupportedEncodingException {
		return changeCharset(str, "GBK");
	}

	public static final String changeCharset(String str, String newCharset) throws UnsupportedEncodingException {
		if (str != null) {
			byte[] bs = str.getBytes();
			return new String(bs, newCharset);
		} else {
			return null;
		}
	}

	public static final String getDefaultCharSet() throws UnsupportedEncodingException {
		OutputStreamWriter writer = new OutputStreamWriter(new ByteArrayOutputStream(), "UTF-8");
		String enc = writer.getEncoding();
		return enc;
	}

	public static final String changeCharset(String str, String oldCharset, String newCharset)
			throws UnsupportedEncodingException {
		if (str != null) {
			byte[] bs = str.getBytes(oldCharset);
			return new String(bs, newCharset);
		} else {
			return null;
		}
	}

	public static final String toGBKWithUTF8(String input) throws UnsupportedEncodingException {
		return Strings.isNullOrEmpty(input) ? "" : new String(input.getBytes("ISO-8859-1"), "GBK");
	}

	public static final String toUnicodeWithGBK(String input) throws UnsupportedEncodingException {
		return Strings.isNullOrEmpty(input) ? "" : new String(input.getBytes("GBK"), "ISO-8859-1");
	}
	
}
